package com.bruce.ai.alibaba.agentcard.discovery.config;

import java.util.Properties;
import java.util.Map;
import java.util.HashMap;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.ai.AiFactory;
import com.alibaba.nacos.api.ai.AiService;
import com.alibaba.nacos.api.ai.model.a2a.AgentCard;
import com.alibaba.nacos.api.exception.NacosException;
import com.bruce.ai.alibaba.agentcard.discovery.client.A2AClient;
import com.bruce.ai.alibaba.agentcard.discovery.config.A2AClientConfig;
import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
public class DiscoveryConfig {

    @Value("${alibaba.a2a.nacos.server-addr}")
    private  String serverAddr ;
    @Value("${alibaba.a2a.nacos.username}")
    private  String username;
    @Value("${alibaba.a2a.nacos.password}")
    private  String password ;
    @Value("${alibaba.a2a.nacos.namespace}")
    private  String namespace;
    @Value("${alibaba.a2a.target-agent:}")
    private  String targetAgent;

    @Bean
    public AiService aiService() throws NacosException{
        Properties properties = new Properties() ;
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, serverAddr) ;
        properties.setProperty(PropertyKeyConst.USERNAME, username) ;
        properties.setProperty(PropertyKeyConst.PASSWORD, password) ;
        properties.setProperty(PropertyKeyConst.NAMESPACE, namespace) ;
        return AiFactory.createAiService(properties);
    }

    @Bean
    public A2AClient a2AClient(AiService aiService) throws NacosException{
        System.out.println("=== A2A Client Configuration ===");
        System.out.println("Nacos Server: " + serverAddr);
        System.out.println("Namespace: " + namespace);
        System.out.println("Username: " + username);
        System.out.println("Target Agent: " + targetAgent);
        
        // 首先尝试通过 Nacos AI Service 获取 AgentCard
        AgentCard agentCard = null;
        if (targetAgent != null && !targetAgent.trim().isEmpty()) {
            try {
                System.out.println("Trying to get AgentCard via Nacos AI Service: " + targetAgent.trim());
                agentCard = aiService.getAgentCard(targetAgent.trim());
                if (agentCard != null) {
                    System.out.println("Successfully found AgentCard via Nacos AI Service: " + agentCard.getName() + " at " + agentCard.getUrl());
                } else {
                    System.out.println("AgentCard not found via Nacos AI Service, trying HTTP API: " + targetAgent.trim());
                    // 如果 AI Service 找不到，尝试 HTTP API
                    boolean found = queryAgentCardViaHttp(targetAgent.trim());
                    if (found) {
                        System.out.println("Successfully found AgentCard via HTTP API: " + targetAgent.trim());
                        // 创建一个 AgentCard 对象，设置基本信息
                        agentCard = new AgentCard();
                        agentCard.setName(targetAgent.trim());
                        agentCard.setUrl("http://localhost:9093"); // register 应用的 URL
                    } else {
                        System.out.println("AgentCard not found via HTTP API: " + targetAgent.trim());
                    }
                }
            } catch (Exception e) {
                System.out.println("Failed to get AgentCard via Nacos AI Service: " + e.getMessage());
                // 尝试 HTTP API 作为备选方案
                try {
                    boolean found = queryAgentCardViaHttp(targetAgent.trim());
                    if (found) {
                        System.out.println("Successfully found AgentCard via HTTP API: " + targetAgent.trim());
                        agentCard = new AgentCard();
                        agentCard.setName(targetAgent.trim());
                        agentCard.setUrl("http://localhost:9093"); // register 应用的 URL
                    }
                } catch (Exception httpE) {
                    System.out.println("Failed to query AgentCard via HTTP API: " + httpE.getMessage());
                    throw new RuntimeException("Failed to get AgentCard via both AI Service and HTTP API", httpE);
                }
            }
        } else {
            throw new RuntimeException("Target agent name is required");
        }
        
        if (agentCard == null) {
            throw new RuntimeException("AgentCard not found: " + targetAgent);
        }
        
        A2AClientConfig config = new A2AClientConfig();
        return new A2AClient(agentCard, config, "discovery-agent");
    }
    
    /**
     * 使用 HTTP REST API 查询 AgentCard，与 register 应用保持一致
     */
    private boolean queryAgentCardViaHttp(String agentName) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        ObjectMapper objectMapper = new ObjectMapper();
        
        // 构建查询 URL - 使用与 register 应用相同的 A2A API
         String baseUrl = "http://" + serverAddr + "/nacos/v3/admin/ai/a2a";
        
        // 构建 AgentCard JSON 对象
        Map<String, Object> agentCard = new HashMap<>();
        agentCard.put("name", agentName);
        agentCard.put("version", "1.0");
        agentCard.put("protocolVersion", "1.0");
        agentCard.put("preferredTransport", "http");
        agentCard.put("url", "http://127.0.0.1:9093");
        
        // 将 agentCard 转换为 JSON 字符串并作为表单参数发送
        String agentCardJson = objectMapper.writeValueAsString(agentCard);
        
        // 构建表单数据
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("agentCard", agentCardJson);
        params.add("username", username);
        params.add("password", password);
        params.add("namespace", namespace);
        
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
        
        try {
            ResponseEntity<String> response = restTemplate.exchange(
                baseUrl, HttpMethod.POST, request, String.class);
            
            System.out.println("HTTP API Query Response: " + response.getBody());
            return response.getStatusCode().is2xxSuccessful();
            
        } catch (Exception e) {
            System.out.println("HTTP API Query failed: " + e.getMessage());
            // 检查是否是 409 Conflict（AgentCard 已存在），这种情况应该视为成功
            if (e.getMessage().contains("409") && e.getMessage().contains("already exist")) {
                System.out.println("AgentCard already exists (409 Conflict) - treating as success");
                return true;
            }
            return false;
        }
    }

}
